import {
  AfterContentInit,
  AfterViewInit,
  Component,
  ContentChildren,
  ElementRef,
  Input,
  QueryList,
  TemplateRef,
  ViewChild,
  ViewChildren,
  ViewContainerRef
} from '@angular/core';
import { ReplaySubject, Subscription } from 'rxjs';
import { TabItemDirective } from './tab-item.directive';

@Component({
  selector: 'app-sub-nav-tab',
  templateUrl: './sub-nav-tab.component.html',
  styleUrls: ['./sub-nav-tab.component.scss']
})
export class SubNavTabComponent implements AfterContentInit {
  @Input() breadcrumbIconType: string;
  @Input() primaryTitle: string;

  @ContentChildren(TabItemDirective) tabItems: QueryList<TabItemDirective>;

  private currentSecondaryTitle = new ReplaySubject<string>(1);
  currentSecondaryTitle$ = this.currentSecondaryTitle.asObservable();

  private currentTabItemContent = new ReplaySubject<TemplateRef<any>>(1);
  currentTabItemContent$ = this.currentTabItemContent.asObservable();

  private currentTabItemIndex = new ReplaySubject<number>(1);
  currentTabItemIndex$ = this.currentTabItemIndex.asObservable();

  private subscriptions: Subscription[] = [];

  switchToTab(index: number) {
    const item = this.tabItems.toArray()[index];
    this.currentSecondaryTitle.next(item.title);
    this.currentTabItemContent.next(item.templateRef);
    this.currentTabItemIndex.next(index);
  }

  ngAfterContentInit() {
    if (this.tabItems.length > 0) {
      this.switchToTab(0);
    }
  }
}
